package com.newlink.building.library_rino

import android.content.Context
import android.util.Log
import com.newlink.building.common_base.event.CallSipBean
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_CALL_SEND_SIP_BODY
import com.newlink.building.common_base.utils.SingletonHolder
import org.greenrobot.eventbus.EventBus

/**
 * Created by xiaodong on 2024/5/23.
 */
class LoopBackManager private constructor(private val context: Context) {
    /**
     * 单例
     */
    companion object : SingletonHolder<LoopBackManager, Context>(::LoopBackManager)

    private external fun nativeInitClass(): Int

    external fun nativeLbInit(listenPort: Int): Int

    external fun nativeLbUnInit(): Int

    //接收到对端mqtt消息,需要平台库处理成sip消息
    external fun nativeMqttMsgIncoming(mqttMsg: String): Int

    //通知底层mqtt client时候连接成功
    external fun nativeMqttRegStatus(success: Int): Int

    //sip消息转换成mqtt消息回调方法
    fun onMqttMessageCallback(
        sipBody: String,
        from: String,
        to: String,
        callId: String,
        method: Int
    ) {
        Log.e(
            "LoopBackManager",
            "onMqttMessageCallback from:$from to:$to callId:$callId method:$method sipBody:$sipBody"
        )
        val sipContent =
            CallSipBean(from = from, to = to, callId = callId, sipType = method, sipBody = sipBody)
        val sipMsgEvent = MessageEvent(TYPE_CALL_SEND_SIP_BODY, sipContent)
        EventBus.getDefault().post(sipMsgEvent)
    }

//    private fun convertToSipMethod(method: Int, sipBody: String): String {
//        return when (method) {
//            0 -> "REGISTER"
//            1 -> "INVITE"
//            2 -> "BYE"
//            else -> {
//                if (sipBody.startsWith("CANCEL")) {
//                    "CANCEL"
//                } else {
//                    "OTHRE"
//                }
//            }
//        }
//    }

    init {
        //实现sip消息和mqtt消息之间的转换
        System.loadLibrary("sip2mqtt")
        nativeInitClass()
    }
}